<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        
    </style>
</head>
<body>
    <input type="button" id="btn1" value="成功">
    <input type="button" id="btn2" value="失败">
</body>
<script>

    const btn1 = document.getElementById("btn1");
    const btn2 = document.getElementById("btn2");

    btn1.onclick = function(){
        const t1 = new Toast({
            text:"成功了",
            color: "green",
            position: "top"
        });
        const t2 = new Toast({
            text:"成功了",
            color: "green",
            position: "top"
        });
        console.log(t1 === t2)
    }
    btn2.onclick = function(){
        new Toast({
            text:"失败了",
            color: "red",
            position: "center"
        });
    }

    function Toast(ops={}){
        // 判断是否存在要控制的单例对象
        if(!Toast.obj){
            // 不存在就创建
            Toast.obj = {};
            Toast.obj.div = document.createElement("dialog");
            document.body.appendChild(Toast.obj.div);
        }
        // 处理参数
        const {text="提示", color="#eee", position="top"} = ops;

        // 控制元素样式
        Toast.obj.div.innerHTML = text;
        Toast.obj.div.style.background = color;
        Toast.obj.div.style.borderColor = color;
        Toast.obj.div.style.top = (position==="top" ? 30 : 200) + "px"
        Toast.obj.div.style.display = "block";

        // 隐藏提示框
        clearTimeout(Toast.obj.t);
        Toast.obj.t = setTimeout(()=>{
            Toast.obj.div.style.display = "none";
        }, 2000);
        // 返回控制的单例对象
        return Toast.obj
    }
</script>
</html>